// index.js - 首页(默认展示记账功能)
import { getEnabledFeatures, navigateToFeature } from '../../utils/feature-config'

Page({  
  data: {
    // 功能列表数据从配置文件加载
    features: [],
    // 当前显示的功能
    currentFeature: 'accounting',
    currentFeatureName: '记账本',
    // 功能菜单显示状态
    showFeatureMenu: false,
    
    // 记账功能数据
    currentMonth: '',
    totalIncome: 0,
    totalExpense: 0,
    bills: [],
    allBills: [],
    filterGranularity: 'day', // 'day' | 'month'
    selectedDate: '',
    statsTitle: '',
    
    // 添加账单弹窗
    showAddBillModal: false,
    billForm: {
      type: 0, // 0-支出, 1-收入
      amount: '',
      icon: 'eat',
      description: '',
      datetime: '', // YYYY-MM-DD HH:mm:ss
      timeDisplay: '',
      timeIndex: [0, 0, 0, 0, 0] // [年, 月, 日, 时, 分]
    },
    timeColumns: [[], [], [], [], []], // 时间选择器的列数据
    accountingIcons: [
      { name: 'eat'},
      { name: 'juice'},
      { name: 'gongzi'},
      { name: 'usdt'},
      { name: 'stock'},
      { name: 'jijin'},
      { name: 'shopping'},
      { name: 'mobile'},
      { name: 'vip'},
      { name: 'transfer'},
      { name: 'hongbao'},
      { name: 'gift'},
      { name: 'house'},
      { name: 'dian'},
      { name: 'car'},
      { name: 'bus'},
      { name: 'airplane'},
      { name: 'subway'},
      { name: 'bicycle'},
      { name: 'diandongche'},
      { name: 'kuaidi'},
      { name: 'menpiao'},
      { name: 'game'},
      { name: 'doctor'},
      { name: 'dog'},
      { name: 'code'}
    ],
    
    // 账单操作弹窗
    showBillActionModal: false,
    selectedBill: {},
    
    // 退款弹窗
    showRefundModal: false,
    refundAmount: '',
    availableRefundAmount: 0, // 可退金额
    
    // 会员提醒功能数据
    subscriptions: [],
    expiringSoon: [],
    totalMonthlyFee: 0,
    
    // 密码管理功能数据
    passwords: [],
    searchKeyword: ''
  },

  onLoad(options) {
    // 检查登录态
    const token = wx.getStorageSync('token')
    if (!token) {
      // 没有token，不加载数据，等待app.js跳转到登录页
      return
    }
    
    // 页面加载时的初始化逻辑
    this.loadFeatures()
    this.initAccountingData()
    // 初始化后立即加载数据
    this.loadAccountingData()
  },

  onShow() {
    // 页面显示时刷新数据(首次加载已在onLoad中处理)
    // 只有非首次进入时才刷新
  },

  /**
   * 加载功能列表
   */
  loadFeatures() {
    const features = getEnabledFeatures()
    this.setData({ features })
  },

  /**
   * 切换功能菜单显示
   */
  toggleFeatureMenu() {
    this.setData({
      showFeatureMenu: !this.data.showFeatureMenu
    })
  },

  /**
   * 阻止事件冒泡
   */
  stopPropagation() {
    // 阻止冒泡
  },

  /**
   * 切换功能 - 在首页内切换显示内容
   */
  switchFeature(e) {
    const { id, name } = e.currentTarget.dataset
    
    // 更新当前功能状态
    this.setData({
      currentFeature: id,
      currentFeatureName: name,
      showFeatureMenu: false
    })
    
    // 根据功能加载对应数据
    if (id === 'accounting') {
      this.loadAccountingData()
    } else if (id === 'membership') {
      this.loadMembershipData()
    } else if (id === 'password') {
      this.loadPasswordData()
    }
  },

  /**
   * 导航到功能详情页(不再需要,已在switchFeature中处理)
   */
  navigateToFeature(e) {
    const { id } = e.currentTarget.dataset
    navigateToFeature(id)
  },

  /**
   * 初始化记账数据
   */
  initAccountingData() {
    const now = new Date()
    const selectedDate = this.formatDate(now)
    const statsTitle = this.formatStatsTitle(selectedDate, 'day')
    this.setData({
      selectedDate,
      statsTitle,
      currentMonth: statsTitle // 兼容旧模板字段
    })
  },

  /**
   * 加载记账数据
   */
  loadAccountingData() {
    // 检查登录态
    const token = wx.getStorageSync('token')
    if (!token) {
      console.log('未登录，跳过加载记账数据')
      return
    }
    
    const { filterGranularity, selectedDate } = this.data
    
    // 如果没有日期,使用今天
    if (!selectedDate) {
      this.initAccountingData()
      // 递归调用,此时selectedDate已经设置
      setTimeout(() => this.loadAccountingData(), 100)
      return
    }

    const timeRange = filterGranularity
    const time = selectedDate

    // 调用全局请求方法
    const app = getApp()
    app.request({
      url: `/api/assets/accounting?timeRange=${timeRange}&time=${time}`,
      method: 'GET'
    }).then(res => {
      const responseData = res.data
      
      if (responseData && responseData.success && responseData.data) {
        const { list, total_expenses, total_revenues } = responseData.data
        
        // 处理账单列表数据
        const processedBills = (list || []).map(bill => {
          const type = bill.type === 1 ? 'income' : 'expense'
          const amount = Number(bill.amount || 0) / 100
          const refund = Number(bill.refund || 0) / 100
          
          return {
            id: bill.id,
            type,
            svg: bill.icon || 'accounting',
            amount,
            refund: refund > 0 ? refund : undefined,
            remark: bill.description || '未备注',
            date: bill.created_at || '',
            displayAmount: `${type === 'expense' ? '-' : '+'}${amount.toFixed(2)}`,
            refundLabel: refund > 0 ? `退款 ¥${refund.toFixed(2)}` : '',
            hasRefund: refund > 0
          }
        })

        this.setData({
          bills: processedBills,
          allBills: processedBills,
          totalIncome: Number(total_revenues || 0),
          totalExpense: Number(total_expenses || 0)
        })
      } else {
        wx.showToast({
          title: (responseData && responseData.message) || '加载失败',
          icon: 'none'
        })
        this.setData({
          bills: [],
          allBills: [],
          totalIncome: 0,
          totalExpense: 0
        })
      }
    }).catch(err => {
      console.error('加载记账数据失败:', err)
      wx.showToast({
        title: '网络请求失败',
        icon: 'none'
      })
      this.setData({
        bills: [],
        allBills: [],
        totalIncome: 0,
        totalExpense: 0
      })
    })
  },

  /**
   * 根据筛选条件重新加载数据
   */
  applyFilters() {
    this.loadAccountingData()
  },

  /**
   * 切换按日/按月
   */
  setFilterGranularity(e) {
    const { granularity } = e.currentTarget.dataset
    if (!granularity || (granularity !== 'day' && granularity !== 'month')) return
    
    const { selectedDate } = this.data
    let nextSelected = selectedDate
    
    if (granularity === 'month') {
      nextSelected = selectedDate.slice(0, 7)
    } else {
      nextSelected = this.formatDate(new Date())
    }
    
    const statsTitle = this.formatStatsTitle(nextSelected, granularity)
    this.setData({ 
      filterGranularity: granularity, 
      selectedDate: nextSelected,
      statsTitle,
      currentMonth: statsTitle
    }, () => {
      this.applyFilters()
    })
  },

  /**
   * 日期选择回调
   */
  onDateChange(e) {
    const value = e.detail.value
    const { filterGranularity } = this.data
    const statsTitle = this.formatStatsTitle(value, filterGranularity)
    
    this.setData({ 
      selectedDate: value,
      statsTitle,
      currentMonth: statsTitle
    }, () => {
      this.applyFilters()
    })
  },

  /**
   * 格式化日期为 YYYY-MM-DD
   */
  formatDate(date) {
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${y}-${m}-${day}`
  },

  /**
   * 根据筛选条件生成统计标题
   */
  formatStatsTitle(value, granularity) {
    if (granularity === 'month') {
      const [y, m] = value.split('-')
      return `${y}年${m}月`
    }
    const [y, m, d] = value.split('-')
    return `${y}年${m}月${d}日`
  },

  /**
   * 初始化时间选择器数据
   */
  initTimePickerData() {
    const now = new Date()
    const currentYear = now.getFullYear()
    const currentMonth = now.getMonth()
    const currentDay = now.getDate() - 1
    const currentHour = now.getHours()
    const currentMinute = now.getMinutes()

    // 年份：前5年到后1年
    const years = []
    for (let i = currentYear - 5; i <= currentYear + 1; i++) {
      years.push(i + '年')
    }

    // 月份：1-12月
    const months = []
    for (let i = 1; i <= 12; i++) {
      months.push(i + '月')
    }

    // 日期：1-31日
    const days = []
    for (let i = 1; i <= 31; i++) {
      days.push(i + '日')
    }

    // 小时：0-23
    const hours = []
    for (let i = 0; i < 24; i++) {
      hours.push(String(i).padStart(2, '0') + '时')
    }

    // 分钟：0-59
    const minutes = []
    for (let i = 0; i < 60; i++) {
      minutes.push(String(i).padStart(2, '0') + '分')
    }

    // 设置默认时间为当前时间
    const timeIndex = [5, currentMonth, currentDay, currentHour, currentMinute]
    const timeDisplay = this.formatTimeDisplay(now)

    this.setData({
      timeColumns: [years, months, days, hours, minutes],
      'billForm.timeIndex': timeIndex,
      'billForm.timeDisplay': timeDisplay,
      'billForm.datetime': this.formatDateTime(now)
    })
  },

  /**
   * 格式化时间显示
   */
  formatTimeDisplay(date) {
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    const h = String(date.getHours()).padStart(2, '0')
    const min = String(date.getMinutes()).padStart(2, '0')
    return `${y}年${m}月${d}日 ${h}:${min}`
  },

  /**
   * 格式化为数据库格式
   */
  formatDateTime(date) {
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    const h = String(date.getHours()).padStart(2, '0')
    const min = String(date.getMinutes()).padStart(2, '0')
    const s = String(date.getSeconds()).padStart(2, '0')
    return `${y}-${m}-${d} ${h}:${min}:${s}`
  },

  /**
   * 时间选择器列变化
   */
  onTimeColumnChange(e) {
    const { column, value } = e.detail
    const timeIndex = [...this.data.billForm.timeIndex]
    const timeColumns = [...this.data.timeColumns]
    
    timeIndex[column] = value

    // 如果改变了年月，需要更新日期列表
    if (column === 0 || column === 1) {
      const year = parseInt(timeColumns[0][timeIndex[0]])
      const month = timeIndex[1] + 1
      const daysInMonth = new Date(year, month, 0).getDate()
      
      const days = []
      for (let i = 1; i <= daysInMonth; i++) {
        days.push(i + '日')
      }
      
      // 如果当前选中的日期超过了新月份的天数，调整为最后一天
      if (timeIndex[2] >= daysInMonth) {
        timeIndex[2] = daysInMonth - 1
      }
      
      // 更新日期列
      timeColumns[2] = days
      
      this.setData({
        timeColumns: timeColumns,
        'billForm.timeIndex': timeIndex
      })
    } else {
      this.setData({
        'billForm.timeIndex': timeIndex
      })
    }
  },

  /**
   * 时间选择器确认
   */
  onTimeChange(e) {
    const { value } = e.detail
    const { timeColumns } = this.data
    
    const year = parseInt(timeColumns[0][value[0]])
    const month = value[1] + 1
    const day = value[2] + 1
    const hour = value[3]
    const minute = value[4]
    
    const date = new Date(year, month - 1, day, hour, minute, 0)
    const timeDisplay = this.formatTimeDisplay(date)
    const datetime = this.formatDateTime(date)
    
    this.setData({
      'billForm.timeIndex': value,
      'billForm.timeDisplay': timeDisplay,
      'billForm.datetime': datetime
    })
  },
  /**
   * 打开添加账单弹窗
   */
  openAddBillModal() {
    // 初始化时间选择器
    this.initTimePickerData()
    
    this.setData({
      showAddBillModal: true,
      'billForm.type': 0,
      'billForm.amount': '',
      'billForm.icon': 'eat',
      'billForm.description': ''
    })
  },

  /**
   * 关闭添加账单弹窗
   */
  closeAddBillModal() {
    this.setData({
      showAddBillModal: false
    })
  },

  /**
   * 阻止事件冒泡
   */
  stopPropagation() {
    // 阻止冒泡
  },

  /**
   * 阻止滚动穿透(只阻止遮罩层滚动)
   */
  preventTouchMove(e) {
    // 仅阻止事件冒泡,不返回 false
  },

  /**
   * 选择账单类型
   */
  selectBillType(e) {
    const { type } = e.currentTarget.dataset
    this.setData({
      'billForm.type': type
    })
  },

  /**
   * 金额输入
   */
  onBillAmountInput(e) {
    let value = e.detail.value
    // 只允许数字和小数点
    value = value.replace(/[^\d.]/g, '')
    // 只允许一个小数点
    const parts = value.split('.')
    if (parts.length > 2) {
      value = parts[0] + '.' + parts.slice(1).join('')
    }
    // 限制小数点后两位
    if (parts.length === 2 && parts[1].length > 2) {
      value = parts[0] + '.' + parts[1].substring(0, 2)
    }
    this.setData({
      'billForm.amount': value
    })
  },

  /**
   * 选择账单图标
   */
  selectBillIcon(e) {
    const { name } = e.currentTarget.dataset
    this.setData({
      'billForm.icon': name
    })
  },

  /**
   * 描述输入
   */
  onBillDescriptionInput(e) {
    this.setData({
      'billForm.description': e.detail.value
    })
  },

  /**
   * 提交添加账单
   */
  submitAddBill() {
    const { type, amount, icon, description, datetime } = this.data.billForm

    // 校验金额
    if (!amount || Number(amount) <= 0) {
      wx.showToast({
        title: '请输入有效金额',
        icon: 'none'
      })
      return
    }

    // 将金额从元转为分
    const amountInCents = Math.round(Number(amount) * 100)

    wx.showLoading({ title: '添加中...' })

    const app = getApp()
    app.request({
      url: '/api/assets/accounting',
      method: 'POST',
      data: {
        type,
        amount: amountInCents,
        icon,
        description: description || '未备注',
        created_at: datetime
      }
    }).then(res => {
      wx.hideLoading()
      const responseData = res.data
      
      if (responseData && responseData.success) {
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        })
        this.closeAddBillModal()
        // 重新加载数据
        this.loadAccountingData()
      } else {
        wx.showToast({
          title: responseData.message || '添加失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('添加账单失败:', err)
      wx.showToast({
        title: '网络请求失败',
        icon: 'none'
      })
    })
  },

  /**
   * 添加账单(旧方法,保留兼容)
   */
  addBill() {
    this.openAddBillModal()
  },

  /**
   * 查看账单详情（已废弃，改用操作弹窗）
   */
  viewBillDetail(e) {
    const { id } = e.currentTarget.dataset
    console.log('查看账单详情:', id)
    wx.showToast({
      title: '查看账单详情功能开发中',
      icon: 'none'
    })
  },

  /**
   * 打开账单操作弹窗
   */
  openBillActionModal(e) {
    const { id, item } = e.currentTarget.dataset
    this.setData({
      selectedBill: item,
      showBillActionModal: true
    })
  },

  /**
   * 关闭账单操作弹窗
   */
  closeBillActionModal() {
    this.setData({
      showBillActionModal: false,
      selectedBill: {}
    })
  },

  /**
   * 确认删除账单
   */
  confirmDeleteBill() {
    const { selectedBill } = this.data
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除这条账单吗？\n金额：${selectedBill.displayAmount}\n备注：${selectedBill.remark}`,
      confirmText: '删除',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          this.deleteBill(selectedBill.id)
        }
      }
    })
  },

  /**
   * 删除账单
   */
  deleteBill(billId) {
    wx.showLoading({ title: '删除中...' })

    const app = getApp()
    app.request({
      url: `/api/assets/accounting/${billId}`,
      method: 'DELETE'
    }).then(res => {
      wx.hideLoading()
      const responseData = res.data
      
      if (responseData && responseData.success) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
        // 关闭操作弹窗
        this.closeBillActionModal()
        // 重新加载数据
        this.loadAccountingData()
      } else {
        wx.showToast({
          title: responseData.message || '删除失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('删除账单失败:', err)
      wx.showToast({
        title: '网络请求失败',
        icon: 'none'
      })
    })
  },

  /**
   * 打开退款弹窗
   */
  openRefundModal() {
    const { selectedBill } = this.data
    
    // 计算可退金额 = 原金额 - 已退款金额
    const availableRefundAmount = (selectedBill.amount - (selectedBill.refund || 0)).toFixed(2)
    
    // 关闭操作弹窗
    this.setData({
      showBillActionModal: false,
      showRefundModal: true,
      refundAmount: '',
      availableRefundAmount: availableRefundAmount
    })
  },

  /**
   * 关闭退款弹窗
   */
  closeRefundModal() {
    this.setData({
      showRefundModal: false,
      refundAmount: ''
    })
  },

  /**
   * 退款金额输入
   */
  onRefundAmountInput(e) {
    let value = e.detail.value
    // 只允许数字和小数点
    value = value.replace(/[^\d.]/g, '')
    // 只允许一个小数点
    const parts = value.split('.')
    if (parts.length > 2) {
      value = parts[0] + '.' + parts.slice(1).join('')
    }
    // 限制小数点后两位
    if (parts.length === 2 && parts[1].length > 2) {
      value = parts[0] + '.' + parts[1].substring(0, 2)
    }
    this.setData({
      refundAmount: value
    })
  },

  /**
   * 提交退款
   */
  submitRefund() {
    const { refundAmount, selectedBill, availableRefundAmount } = this.data

    // 校验金额
    if (!refundAmount || Number(refundAmount) <= 0) {
      wx.showToast({
        title: '请输入有效金额',
        icon: 'none'
      })
      return
    }

    // 校验退款金额不能超过可退金额
    if (Number(refundAmount) > Number(availableRefundAmount)) {
      wx.showToast({
        title: `退款金额不能超过可退金额 ¥${availableRefundAmount}`,
        icon: 'none'
      })
      return
    }

    // 计算新的总退款金额 = 原退款金额 + 本次退款金额（单位：元）
    const currentRefund = selectedBill.refund || 0 // 已退款金额（元）
    const newTotalRefund = Number(currentRefund) + Number(refundAmount) // 新的总退款金额（元）
    
    // 将金额从元转为分
    const newTotalRefundInCents = Math.round(newTotalRefund * 100)

    wx.showLoading({ title: '提交中...' })

    const app = getApp()
    app.request({
      url: `/api/assets/accounting/${selectedBill.id}`,
      method: 'PUT',
      data: {
        refund: newTotalRefundInCents
      }
    }).then(res => {
      wx.hideLoading()
      const responseData = res.data
      
      if (responseData && responseData.success) {
        wx.showToast({
          title: '退款成功',
          icon: 'success'
        })
        this.closeRefundModal()
        // 重新加载数据
        this.loadAccountingData()
      } else {
        wx.showToast({
          title: responseData.message || '退款失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('退款失败:', err)
      wx.showToast({
        title: '网络请求失败',
        icon: 'none'
      })
    })
  },

  // ==================== 会员提醒功能 ====================
  
  /**
   * 加载会员订阅数据
   */
  loadMembershipData() {
    // 检查登录态
    const token = wx.getStorageSync('token')
    if (!token) {
      console.log('未登录，跳过加载订阅数据')
      return
    }
    
    wx.showLoading({ title: '加载中...' })

    const app = getApp()
    app.request({
      url: '/api/due/list',
      method: 'GET'
    }).then(res => {
      wx.hideLoading()
      const responseData = res.data
      
      if (responseData && responseData.success && responseData.data) {
        const list = responseData.data.list || []
        
        // 处理订阅列表数据
        const processedSubscriptions = list.map(item => {
          // 将价格从分转为元
          const price = (Number(item.price || 0) / 100).toFixed(2)
          
          // 格式化时间戳为日期字符串
          const endDate = this.formatTimestamp(item.end_at)
          const startDate = this.formatTimestamp(item.start_at)
          
          // 判断是否为自动续订
          const isAutoRenew = item.renew === 1
          
          // 将SVG代码转换为Base64格式的data URI
          const svgBase64 = this.convertSvgToBase64(item.svg)
          
          return {
            id: item.id,
            name: item.name || '未命名',
            price: price,
            svgBase64: svgBase64, // Base64格式的SVG
            cycleText: item.cycle_text ? `/${item.cycle_text}` : '', // 使用后端返回的周期文本
            renewText: item.renew_text || '', // 使用后端返回的续订文本
            isAutoRenew: isAutoRenew, // 是否自动续订
            endDate: endDate,
            startDate: startDate,
            remindDays: item.remind_days || 7,
            status: item.status,
            remark: item.remark || '',
            daysLeft: item.days_left || 0,
            needRemind: item.need_remind || false
          }
        })

        this.setData({
          subscriptions: processedSubscriptions
        })
        
        // 检查即将到期的订阅
        this.checkExpiring()
      } else {
        wx.showToast({
          title: responseData.message || '加载失败',
          icon: 'none'
        })
        this.setData({
          subscriptions: [],
          expiringSoon: []
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('加载订阅数据失败:', err)
      wx.showToast({
        title: '网络请求失败',
        icon: 'none'
      })
      this.setData({
        subscriptions: [],
        expiringSoon: []
      })
    })
  },

  /**
   * 将SVG代码转换为Base64格式的data URI
   */
  convertSvgToBase64(svgString) {
    if (!svgString) {
      // 返回默认图标
      return '/public/svg/membership.svg'
    }
    
    try {
      // 将SVG字符串转换为Base64
      const base64 = wx.arrayBufferToBase64(
        new Uint8Array(
          svgString.split('').map(char => char.charCodeAt(0))
        ).buffer
      )
      return `data:image/svg+xml;base64,${base64}`
    } catch (error) {
      console.error('SVG转换失败:', error)
      return '/public/svg/membership.svg'
    }
  },

  /**
   * 格式化时间戳为日期字符串
   */
  formatTimestamp(timestamp) {
    if (!timestamp) return '未设置'
    const date = new Date(timestamp * 1000)
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}`
  },

  /**
   * 计算订阅的月度总费用（已删除，保留以防需要）
   */
  calculateMembershipTotal() {
    // const { subscriptions } = this.data
    // const total = subscriptions.reduce((sum, s) => sum + Number(s.price || 0), 0)
    // this.setData({ totalMonthlyFee: total })
  },

  /**
   * 检查即将到期的订阅（使用后端返回的need_remind字段）
   */
  checkExpiring() {
    const { subscriptions } = this.data
    
    // 筛选需要提醒的订阅
    const expiring = subscriptions.filter(sub => sub.needRemind === true)

    this.setData({ expiringSoon: expiring })
  },

  /**
   * 添加订阅（占位）
   */
  addSubscription() {
    wx.showToast({
      title: '添加订阅功能开发中',
      icon: 'none'
    })
  },

  /**
   * 查看订阅详情（占位）
   */
  viewSubscriptionDetail(e) {
    const { id } = e.currentTarget.dataset
    wx.showToast({
      title: '查看订阅详情功能开发中',
      icon: 'none'
    })
  },

  // ==================== 密码管家功能 ====================

  /**
   * 加载密码数据
   */
  loadPasswordData() {
    const passwords = [
      {
        id: 1,
        title: '微信',
        account: 'user@example.com',
        password: '********',
        category: '社交',
        icon: '💬',
        lastModified: '2025-10-20'
      },
      {
        id: 2,
        title: '支付宝',
        account: '138****8888',
        password: '********',
        category: '金融',
        icon: '💰',
        lastModified: '2025-10-15'
      },
      {
        id: 3,
        title: 'GitHub',
        account: 'developer',
        password: '********',
        category: '工作',
        icon: '👨‍💻',
        lastModified: '2025-10-10'
      }
    ]

    this.setData({ passwords })
  },

  /**
   * 搜索密码（占位）
   */
  onPasswordSearch(e) {
    const keyword = e.detail.value
    this.setData({ searchKeyword: keyword })
    // TODO: 可在此处按关键词过滤密码列表
  },

  /**
   * 添加密码（占位）
   */
  addPassword() {
    wx.showToast({
      title: '添加密码功能开发中',
      icon: 'none'
    })
  },

  /**
   * 查看密码详情（占位）
   */
  viewPasswordDetail(e) {
    const { id } = e.currentTarget.dataset
    wx.showToast({
      title: '查看密码详情功能开发中',
      icon: 'none'
    })
  },

  /**
   * 添加账单（占位）
   */
  addBill() {
    wx.showToast({
      title: '添加账单功能开发中',
      icon: 'none'
    })
  }
})
